package com.flow.asyncflow.core.utils.threadpool;


import java.util.concurrent.*;

public class ThreadPoolExecutorMain {

    //线程池
    private static ThreadPoolExecutor pool = null;

    private int corePoolSize;//核心线程池大小
    private int maximumPoolSize;//最大线程池大小
    private long keepAliveTime;//线程池中超过corePoolSize数目的空闲线程最大存活时间；可以allowCoreThreadTimeOut(true)使得核心线程有效时间
    private TimeUnit timeUnit;//时间单位配合keepAliveTime 使用
    private BlockingQueue<Runnable> blockingQueue; // 阻塞任务队列
    private ThreadFactory threadFactory;//新建线程工厂
    private RejectedExecutionHandler rejectedExecutionHandler;//当提交任务数超过maximumPoolSize+workQueue之和时，任务会交给RejectedExecutionHandler来处理

    /**
     * 线程池初始化方法
     * <p>
     * corePoolSize 核心线程池大小----10
     * maximumPoolSize 最大线程池大小----30
     * keepAliveTime 线程池中超过corePoolSize数目的空闲线程最大存活时间----30+单位TimeUnit
     * TimeUnit keepAliveTime时间单位----TimeUnit.MINUTES
     * workQueue 阻塞队列----new ArrayBlockingQueue<Runnable>(10)====10容量的阻塞队列
     * threadFactory 新建线程工厂----new CustomThreadFactory()====定制的线程工厂
     * rejectedExecutionHandler 当提交任务数超过maximumPoolSize+workQueue之和时,
     * 即当提交第41个任务时(前面线程都没有执行完,此测试方法中用sleep(100)),
     * 任务会交给RejectedExecutionHandler来处理
     */
    private static void init() {
        pool = new ThreadPoolExecutor(
                2 * 2,
                60,
                15L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new CustomRejectedExecutionHandler());
    }

    public ThreadPoolExecutorMain(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        pool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new CustomRejectedExecutionHandler());
    }

    public ThreadPoolExecutorMain() {
        if (pool == null) {
            pool = new ThreadPoolExecutor(
                    Runtime.getRuntime().availableProcessors() * 2,
                    60,
                    15L,
                    TimeUnit.MILLISECONDS,
                    new ArrayBlockingQueue<>(10),
                    Executors.defaultThreadFactory(),
                    new CustomRejectedExecutionHandler());
        }

    }

    public void destory() {
        if (pool != null) {
            pool.shutdownNow();
        }
    }


    public static ExecutorService getCustomThreadPoolExecutor() {
        if (pool == null) {
            init();
        }
        return pool;
    }

}
